package com.hna.face.controller.sys;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.hna.face.common.utils.MD5Util;
import com.hna.face.model.BfUser;
import com.hna.face.service.IBfUserService;


@Controller
public class LoginController {
	
	@Autowired
	private IBfUserService userService;
	
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public ModelAndView login(BfUser user, HttpSession session,
			HttpServletRequest request) {
		ModelAndView modelView = new ModelAndView();
		modelView.setViewName("/login");
		return modelView;
	}

//	@RequestMapping(value = "/test", method = RequestMethod.POST)
//	@ResponseBody
//	public ModelAndView test(HttpSession session,HttpServletRequest request) {
//		
//		ModelAndView modelView = new ModelAndView();
//		modelView.setViewName("redirect:/login.do");
//		return modelView;
//
//	}
	
	@RequestMapping(value = "/submitLogin", method = RequestMethod.POST)
	@ResponseBody
	public ModelAndView submitLogin(HttpSession session,HttpServletRequest request, BfUser user) {
		
		ModelAndView modelView = new ModelAndView();
		Subject currentUser = SecurityUtils.getSubject();
		
		System.out.println(MD5Util.getMD5String( user.getUserpasswd()));
		UsernamePasswordToken token = new UsernamePasswordToken(
				user.getUsername(), MD5Util.getMD5String( user.getUserpasswd()));
		token.setRememberMe(true);
		try {
			currentUser.login(token);
		} catch (Exception ace) {
			token.clear();
			request.getSession().setAttribute("shiroLoginFailure",
					"userOrPasswdError");
			modelView.setViewName("redirect:/login.do");
			return modelView;
		} 
		if (currentUser.isAuthenticated()) {
			
			Wrapper<BfUser> wrapper=new EntityWrapper<BfUser>();
			wrapper.eq("username", user.getUsername());
			
			List<BfUser> userList1 = userService.selectList(wrapper);
			BfUser userSession = userList1.get(0);
		    
			session.setAttribute("userInfo", userSession);
			modelView.setViewName("redirect:/index.do");
		} else {
			token.clear();
			request.getSession().setAttribute("shiroLoginFailure",
					"userOrPasswdError");
			modelView.setViewName("redirect:/login.do");
		}
		return modelView;

	}
}
